package com.itheima.springboottlias.controller;

import com.itheima.springboottlias.pojo.Dept;
import com.itheima.springboottlias.service.DeptService;
import com.itheima.springboottlias.service.EmpService;
import com.itheima.springboottlias.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Taotao
 * @date 2023/7/15 20:45
 * @desciption: 部门
 */
@RestController
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpService empService;

    @GetMapping
    public Result selectList() {
        /**
         * 查询所有部门列表
         */
        List<Dept> deptList = deptService.selectList();
        return Result.success(deptList);
    }

    /**
     * id删除部门
     *
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    @Transactional
    public Result deleteDept(@PathVariable  Integer id) throws Exception {
//        删除部门
        deptService.deleteDept(id);
//        删除员工
        empService.deleteByDeptId(id);
        int i = 1/0;
        return Result.success();
    }

    /**
     *新增部门
     * @param dept
     */
    @PostMapping
    public Result addDept(@RequestBody Dept dept) {
        deptService.addDept(dept);
        return Result.success();
    }

    /**
     * 根据id查找部门
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result selectById(@PathVariable  Integer id){
        Dept dept = deptService.selectById(id);
        return Result.success(dept);
    }

    /**
     * 根据id修改部门
     * @param dept
     */
    @PutMapping
    public Result updateById(@RequestBody Dept dept){
        deptService.updateById(dept);
        return  Result.success();
    }
}
